package de.upb.messerschmidt.set;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Key;

import de.upb.messerschmidt.set.entity.Contact;
import de.upb.messerschmidt.set.entity.Person;
import de.upb.messerschmidt.set.jdo.PMF;
import de.upb.messerschmidt.set.util.Utils;

/**
 * Registers a {@link Person}'s {@link Contact} via an HttpPost and persists it.
 * 
 * @author Tim Messerschmidt
 * 
 */
public class RegisterContactServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String userString = req.getParameter("user");
		String contactString = req.getParameter("contact");
		
		if (userString != null && contactString != null) {
			Person user = null;
			Person contact = null;
			
			PersistenceManager pm = PMF.get().getPersistenceManager();
			
			Query query = pm.newQuery(Person.class);
			query.setFilter("name == nameParam && prename == prenameParam");
			query.declareParameters("String nameParam, String prenameParam");
			query.setOrdering("name desc");
			
			String[] userArr = Utils.nameParser(userString);
			List<Person> users = (List<Person>) query.execute(userArr[0],
					userArr[1]);
			
			if (!users.isEmpty()) {
				user = users.get(0);
			}
			
			String[] contactArr = Utils.nameParser(contactString);
			List<Person> contacts = (List<Person>) query.execute(contactArr[0],
					contactArr[1]);
			
			if (!contacts.isEmpty()) {
				contact = contacts.get(0);
			}
			
			boolean alreadyExists = false;
			
			if (user != null && contact != null) {
				for (Key key : user.getContacts()) {
					Query contactQuery = pm.newQuery(Contact.class);
					contactQuery.setFilter("key == keyParam");
					contactQuery.declareParameters("Key keyParam");
					contactQuery
							.declareImports("import com.google.appengine.api.datastore.Key");
					List<Contact> contactList = (List<Contact>) contactQuery
							.execute(key);
					if (!contactList.isEmpty()) {
						if (contact.getKey().equals(
								contactList.get(0).getContact())) {
							alreadyExists = true;
						}
					}
				}
			}
			if (alreadyExists) {
				resp.getWriter().println("Contact already saved");
				resp.setStatus(200);
			} else if (user != null && contact != null) {
				if (contact.getKey() == user.getKey()) {
					resp.getWriter().println(
							"A person cannot be his own contact");
					resp.setStatus(200);
				} else {
					Contact userContact = new Contact(user.getKey(),
							contact.getKey());
					
					try {
						pm.makePersistent(userContact);
						user.getContacts().add(userContact.getKey());
						pm.refresh(user);
						resp.setStatus(200);
						resp.getWriter().println(
								"Contact registered successfully");
					} catch (Exception e) {
						e.printStackTrace();
						resp.setStatus(400);
						resp.getWriter().println("Failed to register Contact");
					} finally {
						pm.close();
					}
				}
			}
		}
	}
}
